// pages/gatherHouse/addHouse/addHouse.js
import p from '../../../utils/platform'
import api from '../../../common/api'
import locationBehavior from '../../../behaviors/location';
import { moveHouseLog } from '../../../common/log';
const computedBehavior = require('miniprogram-computed')

const app = getApp()
const errorMsg = {
  "5004": "该房源已出售！"
}
Page({
  behaviors: [computedBehavior, locationBehavior],

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    city: "",
    placeholder: "搜索楼盘名称或经纪人姓名",
    searchTextValue: "",
    MAX_SELECT: 1, //最大保存房源数量
    isLoadHouseDone: false, //加载房源完成
    isLoadingHouse: false, //加载房源中
    refDetailCode: "", //房源的网站来源
    selectedCount: 0,
    pageSize: 10, //单页请求数
    houDelId: null, //搬家成功的房源代理id
    delegationType: "", // 租 or 卖
    selectedHouseIdList: [], //选中的房源ids
    currentSelectId: "",
    isFirstEnter: true,
    isGoCityPage: false,
    isGoSearchPage: false,
  },

  computed: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // PickOutOnSale_AnJuKe
    this.data.refDetailCode = options.refDetailCode
    this.data.delegationType = options.delegationType
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const searchTextValue = app.globalData.gatherHouseSearchValue

    this.getCityBe()
      .then((city) => {
        city = "苏州市" // 写死
        this.setData({
          searchTextValue,
          city
        })
        app.globalData.gatherHouseSearchValue = ""
        this.data.currentSelectId = ""
        this.fetchHouse()

      })
  },

  handleGo() {
    const list = this.data.list.filter((item) => {
      return item.isSelected
    })

    // console.log(list);
    // return 
    if (!list.length) {
      return p.showToast({
        title: '请选择房源',
        icon: 'none',
      })
    }

    this.setData({
      isLoadingHouse: true
    })

    api.importPickOutHouse({ id: list[0].id }, (res) => {
      if (res.data.isSuccess) {
        let houDelId = res.data.content
        console.log("最新房源代理id", houDelId);

        this.data.houDelId = houDelId
        this.setData({
          isLoadHouseDone: true
        })

      } else {
        this.setData({
          isLoadingHouse: false
        })

        p.showToast({
          title: errorMsg[res.data.content] || "录房失败！",
          icon: "none",
        })
      }
    })
  },

  handleLoadHouseDone() {
    this.setData({
      isLoadingHouse: false,
      isLoadHouseDone: false
    })

    setTimeout(() => {
      if (this.data.houDelId) {
        p.navigateTo({
          url: '/pages/addHouse/infoEntryHouse/infoEntryHouse?houDelId=' + this.data.houDelId,
        })
      }
    }, 500)
  },

  hanldeClearSearchValue() {
    this.setData({
      searchTextValue: ""
    })

    this.fetchHouse()
  },

  handleSelect(e) {
    const id = e.currentTarget.dataset.id
    // const index = this.data.list.findIndex((item) => {
    //   return item.id == id
    // })
    this.data.currentSelectId = ""
    this.data.list.forEach((item) => {
      if (item.id == id) {
        item.isSelected = !item.isSelected
      } else {
        item.isSelected = false
      }

      if (item.isSelected) {
        this.data.currentSelectId = id
      }
    })

    this.setData({
      list: this.data.list,
      selectedCount: this.data.currentSelectId ? 1 : 0
    })

    // const isSelected = !this.data.list[index].isSelected
    // if (isSelected) {
    //   let addCount = 1
    //   let _id = this.data.selectedHouseIdList.shift()
    //   if (_id) {
    //     const index = this.data.list.findIndex((item) => {
    //       return item.id == _id
    //     })

    //     this.setData({
    //       ['list[' + index + '].isSelected']: false,
    //     })

    //     addCount = 0
    //   }

    //   this.data.selectedHouseIdList.push(id)
    //   this.setData({
    //     ['list[' + index + '].isSelected']: true,
    //     selectedCount: this.data.selectedCount + addCount
    //   })

    // } else {
    //   let i = this.data.selectedHouseIdList.indexOf(id)
    //   this.data.selectedHouseIdList.splice(i, 1)
    //   this.setData({
    //     ['list[' + index + '].isSelected']: isSelected,
    //     selectedCount: this.data.selectedCount + (isSelected ? 1 : -1)
    //   })
    // }



  },

  handleLocation() {
    this.data.isGoCityPage = true
    p.navigateTo({
      url: `/pages/vieHouse/selectCity/selectCity?city=${this.data.city}&api=getMoveHouse`
    })
  },

  hanldeGotoSearch() {
    this.data.isGoSearchPage = true

    p.navigateTo({ url: `/pages/vieHouse/commonSearch/commonSearch?placeholder=${this.data.placeholder}&appKey=gatherHouseSearchValue&searchTextValue=${this.data.searchTextValue}` })
  },

  fetchHouse() {
    this.setData({
      list: [],
      selectedCount: 0
    })
    this.selectComponent('#com-scroll-content').fetchHouse(1, this.apiFetch.bind(this))
  },
 

  handleData(e) {
    const rows = e.detail
    const result = this.data.list.concat(rows)
    if (this.data.currentSelectId) {
      result.forEach((item) => {
        item.isSelected = item.id == this.data.currentSelectId
      })
    } 
    
    this.setData({
      list: result,
    })

    this.log(result.length)
  },

  apiFetch({ page, pageSize }) {
    return new Promise((resolve, reject) => {
      api.queryHmPickOutHouseInfoServiceByPage({
        pageSize: this.data.pageSize,
        currentPage: page,
        t: {
          cityName: this.data.city,
          brokerOrresblockName: this.data.searchTextValue,
          sourceWebsite: this.data.refDetailCode
        }
      }, (res) => {
        const content = res.data.content
        resolve({
          content: {
            page: content.currentPage,
            rows: content.pages,
            total: content.totalPage
          }
        })
      })
    })
  },

  timeoutFn() {
    this.setData({
      isLoadingHouse: false,
    })
    p.showToast({
      title: "录房超时！",
      icon: "none",
    })
  },

  log(length) {
    // 表示首次进来
    if (this.data.isFirstEnter) {
      this.data.isFirstEnter = false
      moveHouseLog({
        logType: "1",
        sourcePickOutHouse: this.data.refDetailCode,
        cityName: this.data.city,
      })
    }

    // 城市搜索log
    if (this.data.isGoCityPage) {
      this.data.isGoCityPage = false
      moveHouseLog({
        logType: "2",
        sourcePickOutHouse: this.data.refDetailCode,
        cityName: this.data.city,
        resultNum: length,
      })
    }

    // 关键词搜索log
    if (this.data.isGoSearchPage) {
      this.data.isGoSearchPage = false
      moveHouseLog({
        logType: "3",
        sourcePickOutHouse: this.data.refDetailCode,
        cityName: this.data.city,
        searchContent: this.data.searchTextValue,
        resultNum: length,
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

})